package com.example.adminbase.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.adminbase.service.CrudService;
import com.example.adminbase.shiro.JsonResponse;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

public abstract class CrudControllerAdapter<PK extends Serializable, T> {
    abstract CrudService<PK, T> getService();

    @GetMapping("/findById")
    @ResponseBody
    public T findById(PK id) {
        return getService().findById(id);
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResponse save(@RequestBody T record) {
         getService().save(record);
        return new JsonResponse("保存成功");
    }

    @PostMapping("/update")
    @ResponseBody
    public JsonResponse update(@RequestBody T record) {
        getService().update(record);
        return new JsonResponse("更新成功");
    }

    @PostMapping("/updateSelective")
    @ResponseBody
    public JsonResponse updateSelective(@RequestBody T record) {
        getService().updateSelective(record);
        return new JsonResponse("更新成功");
    }

    @PostMapping("/delete")
    @ResponseBody
    public JsonResponse delete(@RequestBody String idJson) {
        JSONObject jsonObject = JSON.parseObject(idJson);
        getService().delete((PK) jsonObject.get("id"));
        return new JsonResponse("删除成功");
    }

    @PostMapping("/deleteWithIds")
    @ResponseBody
    public JsonResponse deleteWithIds(@RequestBody List<PK> ids) {
        getService().deleteWithIds(ids);
        return new JsonResponse("删除成功");
    }
}
